package com.lin.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;

import com.lin.dao.IOrderDao;
import com.lin.dao.OrderDaoImpl;
import com.lin.utils.JdbcUtils;
import com.lin.vo.Book;
import com.lin.vo.Order;
import com.lin.vo.OrderItem;
import com.lin.vo.User;

public class OrderServiceImpl implements IOrderService {
	private IOrderDao orderDao=new OrderDaoImpl();
	@Override
	public void sava(Order order) {
		/**
		 * 由于需要订单表和订单项中同时存储数据,二者有一个失败,就必须回滚,所以需要开启事务
		 */
		Connection connection = null;
		try {
			connection = JdbcUtils.getConnection();
			// 开启事务( 重置成手动提交 )
			connection.setAutoCommit(false);
			orderDao.save(connection,order);
			// 获取订单项list集合
			List<OrderItem> orderItems = order.getOrderItems();
			for(OrderItem orderItem:orderItems){
				orderDao.save(connection, orderItem);
			} 
			// 提交事务
			DbUtils.commitAndCloseQuietly(connection);
		} catch (SQLException e) {
			e.printStackTrace();
			//回滚事务
			DbUtils.rollbackAndCloseQuietly(connection);
		}
	}
	@Override
	public List<Order> findByUid(User user) {
		return orderDao.findByUid(user);
	}
	@Override
	public Order findByOid(String oid) {
		return orderDao.findByOid(oid);
	}
	@Override
	public void updateOrder(Order order) {
		orderDao.updateOrder(order);
		
	}
	@Override
	public List<Order> findByAllOrders() {
		// TODO Auto-generated method stub
		return orderDao.findByAllOrders();
	}
	@Override
	public List<Order> findByAllOrders(int state) {
		// TODO Auto-generated method stub
		return orderDao.findByAllOrders(state);
	}



}
